package com.next.muscu.visual;

import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.next.muscu.Application;

public abstract class AbstractVisualBasicEditorPanel extends JPanel implements IVisualBasicEditorPanel{

	Map<JComponent,List<IValidator>> validators = new HashMap<JComponent,List<IValidator>>(); 
	
	void addField(String label,JComponent c)
	{
		this.add(Box.createRigidArea(new Dimension(20,0)));
		this.add(new JLabel(label));
		this.add(Box.createRigidArea(new Dimension(5,0)));
		this.add(c);
	}
	
	void addField(String label,JComponent c,String tooltip)
	{
		this.add(Box.createRigidArea(new Dimension(20,0)));
		this.add(new JLabel(label));
		this.add(Box.createRigidArea(new Dimension(5,0)));
		c.setToolTipText(tooltip);
		this.add(c);
	}
	void addField(String label,JComponent c,String tooltip,IValidator validator)
	{
		addField(label,c,tooltip);
		addValidator(c,validator);
		
	}
	public boolean validateField()
	{
		boolean retour = true;
		for(JComponent c : validators.keySet())
		{
			List<IValidator> l = validators.get(c);
			Iterator<IValidator> it = l.iterator();
			while(it.hasNext() && retour )
			{
				IValidator validator =it.next();
				retour = validator.run(c);		
				c.setBackground(Color.red);
				if(!retour) Application.getAppl().getUserMessages().add(validator.getErrorMessage());
			}
		}
		return retour;
	}
	
	public void addValidator(JComponent c,IValidator validator)
	{
		List<IValidator> l  = validators.get(c);
		if(l==null)
		{
			l = new ArrayList<IValidator>();
			validators.put(c, l);
		}
		l.add(validator);
		
	}
	public void cleanValidatorForComponent(JComponent c)
	{
		validators.put(c, null);
	}
	public void removeValidator(JComponent c,IValidator validator)
	{
		List<IValidator> l  = validators.get(c);
		if(l!=null)
		{
			l.remove(validator);
		}
	}
	public void cleanValidators()
	{
		validators.clear();
	}
}
